# -* - coding: UTF-8 -* -
#import sys 
#reload(sys)
#sys.setdefaultencoding('utf8')
import threading
import time 
import logging
import queue

#基础线程类
class Thread(threading.Thread):  
	def __init__(self):  
		threading.Thread.__init__(self) 
		self.stop_event = Thread.Event() 
		self.run_event = Thread.Event()
		self.started = False
	@staticmethod
	def Event():
		return threading.Event()
		
	@staticmethod
	def Queue():
		return queue.Queue()
		
	@staticmethod
	def Freeze():
		pass	
		
	def run(self):
		while not self.run_event.is_set():
			while not self.stop_event.is_set(): 
				try:
					self.on_run()
					time.sleep(0.1)
				except Exception as e:
					logging.error('run error:')
					logging.exception(e)
					time.sleep(0.1)
			self.run_event.wait(1)
		logging.info("Thread End")
		
	def start_thread(self):
		self.stop_event.clear()
		if not self.started:
			self.start()
			self.started = True
			self.run_event.clear()
		try:
			self.on_start()
		except Exception as e:
			logging.error('start error:')
			logging.exception(e)
		
	def stop_thread(self):
		self.stop_event.set()
		try:
			self.on_stop()
		except Exception as e:
			logging.error('stop error:')
			logging.exception(e)
	
	def terminate(self):
		self.run_event.set()
		try:
			self.on_terminate()
		except Exception as e:
			logging.error('terminate error:')
			logging.exception(e)

	def on_run(self):
		pass
	def on_start(self):
		pass
	def on_stop(self):
		pass
	def on_terminate(self):
		pass
		